<template>
  <div class="add-internal-production-container">
    <el-container>
      <el-header class="form-header">
        <div class="page-title">新增内部生产</div>
      </el-header>
      
      <el-main class="form-main">
        <div class="form-container">
          <el-form
            ref="formRef"
            :model="formData"
            :rules="formRules"
            label-width="120px"
            class="production-form"
          >
            <!-- 基础信息 -->
            <div class="form-section">
              <div class="section-title">基础信息</div>
              <div class="form-content">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="生产主题" prop="productionSubject">
                      <el-input v-model="formData.productionSubject" placeholder="请输入生产主题" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="生产类型" prop="productionType">
                      <el-select v-model="formData.productionType" placeholder="请选择生产类型" style="width: 100%">
                        <el-option label="批量生产" value="批量生产" />
                        <el-option label="定制生产" value="定制生产" />
                        <el-option label="试验生产" value="试验生产" />
                        <el-option label="紧急生产" value="紧急生产" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="生产单号" prop="productionOrderNo">
                      <el-input v-model="formData.productionOrderNo" placeholder="请输入生产单号或点击生成">
                        <template #append>
                          <el-button @click="generateOrderNo">生成</el-button>
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="截止日期" prop="documentDate">
                      <el-date-picker
                        v-model="formData.documentDate"
                        type="date"
                        placeholder="请选择截止日期"
                        style="width: 100%"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="销售订单" prop="salesOrderNoId">
                      <el-input 
                        :value="formData.salesOrderNoId > 0 ? `销售订单ID: ${formData.salesOrderNoId}` : ''"
                        :placeholder="noSalesOrder ? '不指定销售订单' : '请选择销售订单'" 
                        :readonly="true"
                        :disabled="noSalesOrder"
                        @click="!noSalesOrder && openSalesOrderDialog()"
                      >
                        <template #append>
                          <el-button 
                            :icon="Search" 
                            :disabled="noSalesOrder"
                            @click="openSalesOrderDialog"
                          ></el-button>
                        </template>
                      </el-input>
                      <el-checkbox 
                        v-model="noSalesOrder" 
                        @change="handleNoSalesOrderChange"
                        style="margin-top: 8px;"
                      >
                        不指定销售订单
                      </el-checkbox>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="负责人" prop="responsiblePerson">
                      <el-input v-model="formData.responsiblePerson" placeholder="请输入负责人">
                        <template #append>
                          <el-button :icon="User" @click="selectResponsiblePerson"></el-button>
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="关联项目" prop="associatedProject">
                      <el-input v-model="formData.associatedProject" placeholder="请输入关联项目名称" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="所在部门" prop="initiatingDepartment">
                      <el-input v-model="formData.initiatingDepartment" placeholder="请输入所在部门" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="联系电话" prop="contactPhone">
                      <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="生产部门" prop="productionDepartment">
                      <el-input v-model="formData.productionDepartment" placeholder="请输入生产部门" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="16">
                    <el-form-item label="生产人员" prop="productionPersonnel">
                      <el-input 
                        v-model="formData.productionPersonnel" 
                        type="textarea" 
                        :rows="2"
                        placeholder="请输入生产人员"
                      >
                        <template #append>
                          <el-button :icon="User" @click="selectProductionPersonnel"></el-button>
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="备注" prop="remarks">
                      <el-input 
                        v-model="formData.remarks" 
                        type="textarea" 
                        :rows="3"
                        placeholder="请输入备注"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </div>

            <!-- 生产物品 -->
            <div class="form-section">
              <div class="section-title">
                生产物品
                <div class="section-actions">
                  <el-button type="primary" size="small" @click="addProductItem">添加</el-button>
                  <el-button type="danger" size="small" @click="deleteSelectedProducts">删除</el-button>
                </div>
              </div>
              <div class="table-container">
                <el-table 
                  :data="formData.productItems" 
                  border  
                  stripe 
                  :max-height="300"
                  @selection-change="handleProductSelectionChange"
                >
                  <el-table-column type="selection" width="55" align="center" />
                  <el-table-column prop="index" label="序号" width="80" align="center">
                    <template #default="scope">
                      {{ scope.$index + 1 }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="itemCode" label="物品编号" width="140" align="center" />
                  <el-table-column prop="itemName" label="物品名称" min-width="150" />
                  <el-table-column prop="specification" label="规格型号" width="120" align="center" />
                  <el-table-column prop="unit" label="单位" width="80" align="center" />
                  <el-table-column prop="materialType" label="物料类型" width="100" align="center" />
                  <el-table-column prop="category" label="物品分类" width="100" align="center" />
                  <el-table-column prop="quantity" label="数量" width="80" align="center" />
                  <el-table-column prop="plannedQuantity" label="计划生产数量" width="120" align="center">
                    <template #default="scope">
                      <el-input-number 
                        v-model="scope.row.plannedQuantity" 
                        size="small"
                        :min="1"
                        :precision="0"
                        style="width: 100%"
                        placeholder="请输入"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="deliveryDate" label="交付日期" width="140" align="center" />
                  <el-table-column prop="remark" label="备注" width="150" align="center">
                    <template #default="scope">
                      <el-input 
                        v-model="scope.row.remark" 
                        size="small"
                        style="width: 100%"
                        placeholder="请输入备注"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="inventory" label="库存" width="80" align="center" />
                  <el-table-column label="操作" width="120" align="center">
                    <template #default="scope">
                      <el-button link type="primary" size="small" @click="editProductItem(scope.row)">编辑</el-button>
                      <el-button link type="danger" size="small" @click="deleteProductItem(scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="table-summary">
                  合计 &nbsp;&nbsp;&nbsp;&nbsp; 计划总量: {{ totalProductQuantity }} &nbsp;&nbsp;&nbsp;&nbsp; 计划生产总量: {{ totalPlannedQuantity }}
                </div>
              </div>
            </div>

            <!-- 消耗物品 -->
            <div class="form-section">
              <div class="section-title">
                消耗物品
                <div class="section-actions">
                  <el-button type="primary" size="small" @click="addConsumableItem">添加</el-button>
                  <el-button type="danger" size="small" @click="deleteSelectedConsumables">删除</el-button>
                </div>
              </div>
              <div class="table-container">
                <el-table 
                  :data="formData.consumableItems" 
                  border 
                  stripe 
                  :max-height="300"
                  @selection-change="handleConsumableSelectionChange"
                >
                  <el-table-column type="selection" width="55" align="center" />
                  <el-table-column prop="index" label="序号" width="80" align="center">
                    <template #default="scope">
                      {{ scope.$index + 1 }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="itemCode" label="物品编号" width="140" align="center" />
                  <el-table-column prop="itemName" label="物品名称" min-width="150" />
                  <el-table-column prop="specification" label="规格型号" width="120" align="center" />
                  <el-table-column prop="unit" label="单位" width="80" align="center" />
                  <el-table-column prop="materialType" label="物料类型" width="100" align="center" />
                  <el-table-column prop="category" label="物品分类" width="100" align="center" />
                  <el-table-column prop="quantity" label="数量" width="80" align="center" />
                  <el-table-column prop="warehouse" label="仓库" width="150" align="center">
                    <template #default="scope">
                      <el-select 
                        v-model="scope.row.warehouseId" 
                        size="small"
                        style="width: 100%"
                        placeholder="请选择仓库"
                        clearable
                      >
                        <el-option 
                          v-for="warehouse in warehouseList" 
                          :key="warehouse.id" 
                          :label="warehouse.name" 
                          :value="warehouse.id"
                        />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column prop="plannedQuantity" label="计划消耗数量" width="120" align="center">
                    <template #default="scope">
                      <el-input-number 
                        v-model="scope.row.plannedQuantity" 
                        size="small"
                        :min="1"
                        :precision="0"
                        style="width: 100%"
                        placeholder="请输入"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="actualQuantity" label="实际消耗数量" width="120" align="center">
                    <template #default="scope">
                      <el-input-number 
                        v-model="scope.row.actualQuantity" 
                        size="small"
                        :min="0"
                        :precision="0"
                        style="width: 100%"
                        placeholder="请输入"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="inventory" label="库存" width="80" align="center" />
                  <el-table-column prop="remark" label="备注" width="150" align="center">
                    <template #default="scope">
                      <el-input 
                        v-model="scope.row.remark" 
                        size="small"
                        style="width: 100%"
                        placeholder="请输入备注"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120" align="center">
                    <template #default="scope">
                      <el-button link type="primary" size="small" @click="editConsumableItem(scope.row)">编辑</el-button>
                      <el-button link type="danger" size="small" @click="deleteConsumableItem(scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="table-summary">
                  合计 &nbsp;&nbsp;&nbsp;&nbsp; 计划总量: {{ totalConsumableQuantity }} &nbsp;&nbsp;&nbsp;&nbsp; 计划消耗总量: {{ totalPlannedConsumableQuantity }} &nbsp;&nbsp;&nbsp;&nbsp; 实际消耗总量: {{ totalActualConsumableQuantity }}
                </div>
              </div>
            </div>

            <!-- 附件 -->
            <div class="form-section">
              <div class="section-title">附件</div>
              <div class="form-content">
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="附件上传">
                      <div class="attachment-upload-area">
                        <el-upload
                          ref="uploadRef"
                          class="upload-demo"
                          drag
                          action=""
                          :auto-upload="false"
                          :show-file-list="false"
                          :on-change="handleFileSelect"
                          :accept="'.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.jpg,.jpeg,.png,.gif,.bmp,.zip,.rar'"
                          multiple
                        >
                          <el-icon class="el-icon--upload"><Document /></el-icon>
                          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                          <div class="el-upload__tip">支持多文件上传，文件大小不超过50MB，将立即上传</div>
                        </el-upload>


                        <!-- 已上传文件列表 -->
                        <div v-if="formData.attachments.length > 0" class="uploaded-files">
                          <div class="files-header">
                            <span>已上传文件 ({{ formData.attachments.length }})</span>
                          </div>
                          <div class="files-list">
                            <div v-for="(file, index) in formData.attachments" :key="index" class="file-item">
                              <el-icon><Document /></el-icon>
                              <span class="file-name">{{ file.name }}</span>
                              <span class="file-size">({{ formatFileSize(file.size) }})</span>
                              <span class="upload-time">{{ file.uploadTime }}</span>
                              <el-button 
                                type="danger" 
                                size="small" 
                                link 
                                @click="deleteAttachment(index)"
                              >
                                删除
                              </el-button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </div>
          </el-form>
        </div>
      </el-main>
      
      <el-footer class="form-footer">
        <div class="footer-actions">
          <el-button @click="handleClose" :disabled="submitLoading">关闭</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
        </div>
      </el-footer>
    </el-container>

    <!-- 物品选择对话框 -->
    <el-dialog
      v-model="itemDialogVisible"
      :title="itemDialogTitle"
      width="80%"
      :before-close="() => itemDialogVisible = false"
    >
      <!-- 搜索区域 -->
      <div style="margin-bottom: 16px;">
        <el-row :gutter="16">
          <el-col :span="5">
            <el-input 
              v-model="itemSearch.itemCode" 
              placeholder="请输入物品编号"
              clearable
            />
          </el-col>
          <el-col :span="5">
            <el-input 
              v-model="itemSearch.itemName" 
              placeholder="请输入物品名称"
              clearable
            />
          </el-col>
          <el-col :span="4">
            <el-select 
              v-model="itemSearch.materialType" 
              placeholder="请选择物料类型"
              style="width: 100%"
              clearable
            >
              <el-option label="原材料" value="原材料" />
              <el-option label="半成品" value="半成品" />
              <el-option label="成品" value="成品" />
              <el-option label="物料" value="物料" />
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select 
              v-model="itemSearch.category" 
              placeholder="请选择物品分类"
              style="width: 100%"
              clearable
            >
              <el-option label="原材料" value="1" />
              <el-option label="半成品" value="2" />
              <el-option label="成品" value="3" />
              <el-option label="物料" value="4" />
              <el-option label="家具" value="5" />
              <el-option label="电子产品" value="6" />
              <el-option label="衣物" value="7" />
              <el-option label="食品" value="8" />
              <el-option label="化妆品" value="9" />
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-button type="primary" @click="searchItems">查询</el-button>
            <el-button @click="resetItemSearch">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 表格区域 -->
      <el-table 
        :data="itemList" 
        stripe 
        border 
        style="width: 100%"
        v-loading="itemLoading"
        @selection-change="handleItemSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="itemCode" label="物品编号" width="140" align="center" />
        <el-table-column prop="itemName" label="物品名称" min-width="150" />
        <el-table-column prop="specification" label="规格型号" width="120" align="center" />
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column prop="materialType" label="物料类型" width="100" align="center" />
        <el-table-column prop="inventory" label="库存" width="80" align="center" />
        <el-table-column prop="category" label="物品分类" width="100" align="center" />
      </el-table>

      <!-- 分页区域 -->
      <div style="margin-top: 16px; display: flex; justify-content: space-between; align-items: center;">
        <span>共 {{ itemTotal }} 条数据</span>
        <el-pagination
          v-model:current-page="itemPagination.pageIndex"
          v-model:page-size="itemPagination.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="itemTotal"
          layout="sizes, prev, pager, next, jumper"
          @size-change="handleItemSizeChange"
          @current-change="handleItemCurrentChange"
        />
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="itemDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectItems">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 销售订单选择对话框 -->
    <el-dialog
      v-model="salesOrderDialogVisible"
      title="选择销售订单"
      width="80%"
      :before-close="() => salesOrderDialogVisible = false"
    >
      <!-- 搜索区域 -->
      <div style="margin-bottom: 16px;">
        <el-row :gutter="16">
          <el-col :span="5">
            <el-input 
              v-model="salesOrderSearch.orderNumber" 
              placeholder="请输入销售单号/主题"
              clearable
            />
          </el-col>
          <el-col :span="5">
            <el-input 
              v-model="salesOrderSearch.customerName" 
              placeholder="请输入客户名称"
              clearable
            />
          </el-col>
          <el-col :span="5">
            <el-date-picker
              v-model="salesOrderSearch.orderDate"
              type="date"
              placeholder="请选择销售日期"
              style="width: 100%"
              clearable
            />
          </el-col>
          <el-col :span="5">
            <el-select 
              v-model="salesOrderSearch.status" 
              placeholder="请选择订单状态"
              style="width: 100%"
              clearable
            >
              <el-option label="生产中" value="生产中" />
              <el-option label="已完成" value="已完成" />
              <el-option label="未开始" value="未开始" />
              <el-option label="已取消" value="已取消" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="searchSalesOrders">查询</el-button>
            <el-button @click="resetSalesOrderSearch">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 表格区域 -->
      <el-table 
        :data="salesOrderList" 
        stripe 
        border 
        style="width: 100%"
        v-loading="salesOrderLoading"
        @selection-change="handleSalesOrderSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="orderNo" label="销售单号" width="140" align="center" />
        <el-table-column prop="subject" label="销售订单主题" min-width="180" />
        <el-table-column prop="customerName" label="客户名称" min-width="160" />
        <el-table-column prop="orderDate" label="销售日期" width="120" align="center" />
        <el-table-column prop="status" label="订单状态" width="100" align="center" />
        <el-table-column prop="details" label="物品概要" width="140" align="center" />
      </el-table>

      <!-- 分页区域 -->
      <div style="margin-top: 16px; display: flex; justify-content: space-between; align-items: center;">
        <span>共 {{ salesOrderTotal }} 条数据</span>
        <el-pagination
          v-model:current-page="salesOrderPagination.pageIndex"
          v-model:page-size="salesOrderPagination.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="salesOrderTotal"
          layout="sizes, prev, pager, next, jumper"
          @size-change="handleSalesOrderSizeChange"
          @current-change="handleSalesOrderCurrentChange"
        />
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="salesOrderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectSalesOrder">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, OfficeBuilding, Document, Search } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { getSalesOrders,getSalesOrderItems, getItemss, addInternalProduction, uploadFile,  getDepartments } from '@/Https/server'

const router = useRouter()

// 表单引用
const formRef = ref()

// 提交加载状态
const submitLoading = ref(false)

// 文件上传相关
const uploadRef = ref()

// 表单数据
const formData = reactive({
  productionSubject: '',
  productionType: '',
  productionOrderNo: '',
  documentDate: '',
  salesOrderNoId: 0, // 销售订单ID，对应图一的salesOrderNoId
  responsiblePerson: '',
  associatedProject: '', // 关联项目，对应图一的associatedProject
  initiatingDepartment: '',
  contactPhone: '',
  productionDepartment: '',
  productionPersonnel: '',
  remarks: '',
  createName: '', // 创建人，对应图一的createName
  productItems: [] as any[],
  consumableItems: [] as any[],
  attachments: [] as any[] // 重新添加attachments字段用于文件上传
})

// 表单验证规则
const formRules = {
  productionSubject: [
    { required: true, message: '请输入生产主题', trigger: 'blur' }
  ],
  productionType: [
    { required: true, message: '请选择生产类型', trigger: 'change' }
  ],
  productionOrderNo: [
    { required: true, message: '请输入生产单号', trigger: 'blur' }
  ],
  documentDate: [
    { required: true, message: '请选择截止日期', trigger: 'change' }
  ],
  responsiblePerson: [
    { required: true, message: '请输入负责人', trigger: 'blur' }
  ]
}

// 选中的生产物品
const selectedProducts = ref<any[]>([])
// 选中的消耗物品
const selectedConsumables = ref<any[]>([])

// 部门列表数据
const departmentList = ref<any[]>([])

// 仓库列表数据
const warehouseList = ref<any[]>([
  { id: 1, name: '主仓库' },
  { id: 2, name: '原材料仓库' },
  { id: 3, name: '半成品仓库' },
  { id: 4, name: '成品仓库' },
  { id: 5, name: '备件仓库' }
])

// 物品选择对话框
const itemDialogVisible = ref(false)
const itemDialogTitle = ref('')
const itemLoading = ref(false)
const itemList = ref<any[]>([])
const itemTotal = ref(0)
const selectedItems = ref<any[]>([])
const currentItemType = ref('') // 'product' 或 'consumable'

// 物品搜索条件
const itemSearch = reactive({
  itemCode: '',
  itemName: '',
  materialType: '',
  category: ''
})

// 物品分页
const itemPagination = reactive({
  pageIndex: 1,
  pageSize: 5
})

// 销售订单对话框
  const salesOrderDialogVisible = ref(false)
  const noSalesOrder = ref(false)
  const salesOrderLoading = ref(false)
  const salesOrderList = ref<any[]>([])
  const salesOrderTotal = ref(0)
  const selectedSalesOrder = ref<any>(null)
  
  // 销售订单搜索条件
  const salesOrderSearch = reactive({
    orderNumber: '',
    customerName: '',
    orderDate: '',
    status: ''
  })
  
  // 销售订单分页
  const salesOrderPagination = reactive({
    pageIndex: 1,
    pageSize: 5
  })

// 计算总量
const totalProductQuantity = computed(() => {
  return formData.productItems.reduce((sum, item) => sum + (item.quantity || 0), 0)
})

const totalPlannedQuantity = computed(() => {
  return formData.productItems.reduce((sum, item) => sum + (item.plannedQuantity || 0), 0)
})

const totalConsumableQuantity = computed(() => {
  return formData.consumableItems.reduce((sum, item) => sum + (item.quantity || 0), 0)
})

const totalPlannedConsumableQuantity = computed(() => {
  return formData.consumableItems.reduce((sum, item) => sum + (item.plannedQuantity || 0), 0)
})

const totalActualConsumableQuantity = computed(() => {
  return formData.consumableItems.reduce((sum, item) => sum + (item.actualQuantity || 0), 0)
})

// 生成订单号
const generateOrderNo = () => {
  const now = new Date()
  const dateStr = now.getFullYear().toString() + 
                  (now.getMonth() + 1).toString().padStart(2, '0') + 
                  now.getDate().toString().padStart(2, '0')
  const timeStr = now.getHours().toString().padStart(2, '0') + 
                  now.getMinutes().toString().padStart(2, '0') + 
                  now.getSeconds().toString().padStart(2, '0')
  const orderNo = `SCND${dateStr}${timeStr}${Math.floor(Math.random() * 100).toString().padStart(2, '0')}`
  formData.productionOrderNo = orderNo
  ElMessage.success(`已生成生产单号: ${orderNo}`)
}

// 选择负责人
const selectResponsiblePerson = () => {
  ElMessage.info('选择负责人功能')
}

// 级联选择器配置
const cascaderProps = {
  value: 'values',
  label: 'label',
  children: 'children',
  checkStrictly: false,
  emitPath: false
}

// 获取部门列表
const getDepartmentList = async () => {
  try {
    const response: any = await getDepartments()
    if (response.code == 200) {
      departmentList.value = response.data
    }
  } catch (apiError: any) {
    console.error('获取部门列表失败:', apiError)
    
    // 处理网络错误和服务器错误
    if (apiError.response) {
      const status = apiError.response.status
      ElMessage.error(`获取部门列表失败 (${status}): ${apiError.response.data?.message || '服务器错误'}`)
    } else if (apiError.request) {
      if (apiError.code === 'ECONNABORTED' || apiError.message.includes('timeout')) {
        ElMessage.error('获取部门列表超时，请检查网络连接后重试')
      } else {
        ElMessage.error('网络连接失败，请检查网络连接后重试')
      }
    } else {
      ElMessage.error(`获取部门列表失败: ${apiError.message}`)
    }
  }
}

// 处理所在部门选择变化
const handleInitiatingDepartmentChange = (value: any) => {
  if (value) {
    // 根据选择的值找到对应的部门名称
    const selectedDepartment = findDepartmentByValue(departmentList.value, value)
    formData.initiatingDepartment = selectedDepartment?.label || ''
  } else {
    formData.initiatingDepartment = ''
  }
}

// 处理生产部门选择变化
const handleProductionDepartmentChange = (value: any) => {
  if (value) {
    // 根据选择的值找到对应的部门名称
    const selectedDepartment = findDepartmentByValue(departmentList.value, value)
    formData.productionDepartment = selectedDepartment?.label || ''
  } else {
    formData.productionDepartment = ''
  }
}

// 根据值查找部门信息
const findDepartmentByValue = (list: any[], targetValue: any): any => {
  for (const item of list) {
    if (item.values === targetValue) {
      return item
    }
    if (item.children && item.children.length > 0) {
      const found = findDepartmentByValue(item.children, targetValue)
      if (found) return found
    }
  }
  return null
}

// 根据分类ID获取分类名称
const getClassificationName = (classificationId: number): string => {
  const classificationMap: { [key: number]: string } = {
    1: '原材料',  // 根据API数据，ID为1对应原材料
    2: '半成品', 
    3: '成品',
    4: '物料',
    5: '家具',
    6: '电子产品',
    7: '衣物',
    8: '食品',
    9: '化妆品'
  }
  return classificationMap[classificationId] || ''
}

// 选择生产人员
const selectProductionPersonnel = () => {
  ElMessage.info('选择生产人员功能')
}

// 打开销售订单对话框
const openSalesOrderDialog = () => {
  if (!noSalesOrder.value) {
    salesOrderDialogVisible.value = true
    // 重置搜索条件和分页
    salesOrderSearch.orderNumber = ''
    salesOrderSearch.customerName = ''
    salesOrderSearch.orderDate = ''
    salesOrderSearch.status = ''
    salesOrderPagination.pageIndex = 1
    salesOrderPagination.pageSize = 5
    selectedSalesOrder.value = null
    // 加载数据
    loadSalesOrders()
  }
}

// 加载销售订单数据
const loadSalesOrders = async () => {
  salesOrderLoading.value = true
  try {
    const params = {
      PageIndex: salesOrderPagination.pageIndex,
      PageSize: salesOrderPagination.pageSize,
      OrderNumberOrSubject: salesOrderSearch.orderNumber || '',
      CustomerName: salesOrderSearch.customerName || '',
      StartDate: '',
      EndDate: '',
      OrderStatus: salesOrderSearch.status || ''
    }

    // 使用封装好的 getSalesOrders 函数
    const response: any = await getSalesOrders(params)
    
    console.log('getSalesOrders API响应:', response)
    console.log('响应数据结构:', Object.keys(response || {}))
    
    // 根据API文档，getSalesOrders直接返回数据，不需要.data
    if (response && response.pageData) {
      // 使用新的API返回的销售订单数据
      salesOrderList.value = response.pageData?.map((item: any) => ({
        id: item.id,
        orderNo: item.salesOrderNumber,
        subject: item.orderSubject,
        customerName: item.customerName,
        orderDate: item.createTime ? new Date(item.createTime).toISOString().split('T')[0] : '',
        status: item.orderStatus,
        details: item.itemSummary || ''
      })) || []
      salesOrderTotal.value = response.totalCount || 0
      console.log('处理后的销售订单列表:', salesOrderList.value)
      console.log('销售订单总数:', salesOrderTotal.value)
    } else {
      console.log('销售订单响应数据格式异常:', response)
      ElMessage.error('加载销售订单失败：响应数据格式错误')
      salesOrderList.value = []
      salesOrderTotal.value = 0
    }
  } catch (apiError: any) {
    console.error('加载销售订单错误:', apiError)
    
    // 处理网络错误和服务器错误
    if (apiError.response) {
      const status = apiError.response.status
      ElMessage.error(`加载销售订单失败 (${status}): ${apiError.response.data?.message || '服务器错误'}`)
    } else if (apiError.request) {
      if (apiError.code === 'ECONNABORTED' || apiError.message.includes('timeout')) {
        ElMessage.error('加载销售订单超时，请检查网络连接后重试')
      } else {
        ElMessage.error('网络连接失败，请检查网络连接后重试')
      }
    } else {
      ElMessage.error(`加载销售订单失败: ${apiError.message}`)
    }
    
    salesOrderList.value = []
    salesOrderTotal.value = 0
  } finally {
    salesOrderLoading.value = false
  }
}

// 搜索销售订单
const searchSalesOrders = () => {
  salesOrderPagination.pageIndex = 1
  loadSalesOrders()
}

// 重置销售订单搜索
const resetSalesOrderSearch = () => {
  salesOrderSearch.orderNumber = ''
  salesOrderSearch.customerName = ''
  salesOrderSearch.orderDate = ''
  salesOrderSearch.status = ''
  salesOrderPagination.pageIndex = 1
  loadSalesOrders()
}

// 处理销售订单选择变化
const handleSalesOrderSelectionChange = (selection: any[]) => {
  selectedSalesOrder.value = selection.length > 0 ? selection[0] : null
}

// 处理分页大小变化
const handleSalesOrderSizeChange = (val: number) => {
  salesOrderPagination.pageSize = val
  salesOrderPagination.pageIndex = 1
  loadSalesOrders()
}

// 处理当前页变化
const handleSalesOrderCurrentChange = (val: number) => {
  salesOrderPagination.pageIndex = val
  loadSalesOrders()
}

// 确认选择销售订单
const confirmSelectSalesOrder = () => {
  if (selectedSalesOrder.value) {
    formData.salesOrderNoId = selectedSalesOrder.value.id // 保存销售订单ID
    salesOrderDialogVisible.value = false
    ElMessage.success(`已选择销售订单：${selectedSalesOrder.value.orderNo}`)
  } else {
    ElMessage.warning('请选择一个销售订单')
  }
}

// 选择销售订单
const selectSalesOrder = (order: any) => {
  formData.salesOrderNoId = order.id
  salesOrderDialogVisible.value = false
  ElMessage.success(`已选择销售订单：${order.orderNo}`)
}

// 处理不指定销售订单的变化
const handleNoSalesOrderChange = (value: boolean) => {
  if (value) {
    formData.salesOrderNoId = 0 // 清空销售订单ID
    ElMessage.info('已设置为不指定销售订单')
  }
}

// 添加生产物品
const addProductItem = () => {
  currentItemType.value = 'product'
  itemDialogTitle.value = '选择生产物品'
  itemDialogVisible.value = true
  // 重置搜索条件和分页
  itemSearch.itemCode = ''
  itemSearch.itemName = ''
  itemSearch.materialType = ''
  itemSearch.category = ''
  itemPagination.pageIndex = 1
  itemPagination.pageSize = 5
  selectedItems.value = []
  // 加载数据
  loadItems()
}

// 编辑生产物品
const editProductItem = (item: any) => {
  ElMessage.info('编辑生产物品功能')
}

// 删除生产物品
const deleteProductItem = (index: number) => {
  formData.productItems.splice(index, 1)
}

// 删除选中的生产物品
const deleteSelectedProducts = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要删除的物品')
    return
  }
  
  ElMessageBox.confirm('确定删除选中的生产物品吗？', '确认删除', {
    type: 'warning'
  }).then(() => {
    const selectedIds = selectedProducts.value.map((item: any) => item.itemCode)
    formData.productItems = formData.productItems.filter(item => !selectedIds.includes(item.itemCode))
    ElMessage.success('删除成功')
  })
}

// 生产物品选择变化
const handleProductSelectionChange = (selection: any[]) => {
  selectedProducts.value = selection
}

// 添加消耗物品
const addConsumableItem = () => {
  currentItemType.value = 'consumable'
  itemDialogTitle.value = '选择消耗物品'
  itemDialogVisible.value = true
  // 重置搜索条件和分页
  itemSearch.itemCode = ''
  itemSearch.itemName = ''
  itemSearch.materialType = ''
  itemSearch.category = ''
  itemPagination.pageIndex = 1
  itemPagination.pageSize = 5
  selectedItems.value = []
  // 加载数据
  loadItems()
}

// 编辑消耗物品
const editConsumableItem = (item: any) => {
  ElMessage.info('编辑消耗物品功能')
}

// 删除消耗物品
const deleteConsumableItem = (index: number) => {
  formData.consumableItems.splice(index, 1)
}

// 删除选中的消耗物品
const deleteSelectedConsumables = () => {
  if (selectedConsumables.value.length === 0) {
    ElMessage.warning('请选择要删除的物品')
    return
  }
  
  ElMessageBox.confirm('确定删除选中的消耗物品吗？', '确认删除', {
    type: 'warning'
  }).then(() => {
    const selectedIds = selectedConsumables.value.map((item: any) => item.itemCode)
    formData.consumableItems = formData.consumableItems.filter(item => !selectedIds.includes(item.itemCode))
    ElMessage.success('删除成功')
  })
}

// 消耗物品选择变化
const handleConsumableSelectionChange = (selection: any[]) => {
  selectedConsumables.value = selection
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
}

// 格式化时间
const formatTime = (date: Date) => {
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

// 处理文件选择 - 立即上传文件（参考新增物品管理）
const handleFileSelect = async (file: any) => {
  if (!file.raw) return
  
  // 检查文件大小限制 (50MB)
  const maxSize = 50 * 1024 * 1024
  if (file.raw.size > maxSize) {
    ElMessage.error(`文件 "${file.name}" 大小超过50MB限制`)
    return
  }
  
  // 检查文件类型
  const fileExtension = file.name.toLowerCase().split('.').pop()
  const allowedExts = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'zip', 'rar']
  
  if (!allowedExts.includes(fileExtension)) {
    ElMessage.error(`不支持的文件类型：${fileExtension}`)
    return
  }
  
  // 检查文件是否已存在
  const exists = formData.attachments.some(f => 
    f.name === file.name && f.size === file.size
  )
  
  if (exists) {
    ElMessage.warning(`文件 "${file.name}" 已存在`)
    return
  }
  
  try {
    // 显示上传中消息
    ElMessage.info(`正在上传文件 "${file.name}"...`)
    
    // 立即调用API上传文件
    const response: any = await uploadFile(file.raw)
    
    // 处理响应
    let fileUrl = ''
    if (response && response.data) {
      fileUrl = response.data
    } else if (typeof response === 'string') {
      fileUrl = response
    } else {
      fileUrl = 'uploaded'
    }
    
    // 添加到附件列表（按照后端期望的格式）
    formData.attachments.push({
      name: file.name, // 前端显示用
      size: file.size, // 前端显示用  
      url: fileUrl, // 前端显示用
      uploadTime: formatTime(new Date()), // 前端显示用
      // 后端需要的字段格式
      Filename: file.name,
      Filepath: fileUrl,
      Filesize: file.size
    })
    
    ElMessage.success(`文件 "${file.name}" 上传成功`)
    
  } catch (uploadError: any) {
    console.error(`文件 ${file.name} 上传失败:`, uploadError)
    
    // 处理上传错误
    if (uploadError.response) {
      const status = uploadError.response.status
      if (status === 413) {
        ElMessage.error(`文件 "${file.name}" 太大，上传失败`)
      } else {
        ElMessage.error(`文件 "${file.name}" 上传失败 (${status})`)
      }
    } else if (uploadError.request) {
      if (uploadError.code === 'ECONNABORTED' || uploadError.message.includes('timeout')) {
        ElMessage.error(`文件 "${file.name}" 上传超时`)
      } else {
        ElMessage.error(`文件 "${file.name}" 网络错误`)
      }
    } else {
      ElMessage.error(`文件 "${file.name}" 上传失败`)
    }
  }
}



// 删除附件
const deleteAttachment = (index: number) => {
  const file = formData.attachments[index]
  formData.attachments.splice(index, 1)
  ElMessage.success(`已删除文件：${file.name}`)
}

// 提交表单
const handleSubmit = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 验证必须有生产物品
        if (formData.productItems.length === 0) {
          ElMessage.error('请至少添加一个生产物品')
          return
        }

        // 构建提交数据，严格按照后端InternalProductionInput结构
        const submitData = {
          ProductionSubject: formData.productionSubject,
          ProductionType: formData.productionType,
          ProductionOrderNo: formData.productionOrderNo,
          SalesOrderNoId: (formData.salesOrderNoId && !noSalesOrder.value) ? Number(formData.salesOrderNoId) : null,
          DocumentDate: formData.documentDate ? new Date(formData.documentDate).toISOString() : null,
          AssociatedProject: formData.associatedProject,
          InitiatingDepartment: formData.initiatingDepartment,
          ResponsiblePerson: formData.responsiblePerson,
          ContactPhone: formData.contactPhone,
          ProductionDepartment: formData.productionDepartment,
          ProductionPersonnel: formData.productionPersonnel,
          Remarks: formData.remarks,
          CreateName: formData.createName || formData.responsiblePerson || '系统用户', // 必填字段
          ProductionItems: formData.productItems.map(item => ({
            GoodsId: item.id ? Number(item.id) : null,
            Plannedproduction: Number(item.plannedQuantity || item.quantity || 0),
            Remark: item.remark || ''
          })),
          ConsumableItems: formData.consumableItems.map(item => ({
            GoodsId: item.id ? Number(item.id) : null,
            WarehouseId: item.warehouseId ? Number(item.warehouseId) : null,
            Plannedquantity: Number(item.plannedQuantity || item.quantity || 0),
            Number: Number(item.quantity || 0),
            Remark: item.remark || ''
          })),
          Attachments: formData.attachments.map(attachment => ({
            Filename: attachment.Filename || attachment.name,
            Filepath: attachment.Filepath || attachment.url,
            Filesize: attachment.Filesize || attachment.size
          }))
        }
        // 调用API提交数据
        const response = await addInternalProduction(submitData)
        // 检查响应格式，根据实际API返回格式进行判断
        // 后端返回的是 APIResult<int> 结构：{ code, message, data }
        let responseData: any = response
        
        // 如果response有data属性，说明axios没有被拦截器处理，需要取data
        if (response && typeof response === 'object' && 'data' in response) {
          responseData = (response as any).data
        }
        
        // 处理不同的响应格式
        if (responseData && typeof responseData === 'object' && responseData.code === 200) {
          // 标准的APIResult格式：{ code: 200, message: "...", data: 13 }
          ElMessage.success(`内部生产单创建成功！生产ID: ${responseData.data}`)
          router.push('/ShowInternalProduction')
        } else if (responseData && typeof responseData === 'object' && responseData.code === 500) {
          ElMessage.error(`创建失败: ${responseData.message || '服务器内部错误'}`)
        } else if (responseData && typeof responseData === 'object' && responseData.code === 400) {
          ElMessage.error(`参数错误: ${responseData.message || '请求参数有误'}`)
        } else if (responseData && typeof responseData === 'object' && responseData.code) {
          ElMessage.error(`创建失败 (错误码: ${responseData.code}): ${responseData.message || '未知错误'}`)
        } else if (typeof responseData === 'number' && responseData > 0) {
          // 如果直接返回数字，说明是生产ID，表示创建成功
          ElMessage.success(`内部生产单创建成功！生产ID: ${responseData}`)
          router.push('/ShowInternalProduction')
        } else if (typeof responseData === 'string') {
          // 如果返回字符串，可能是成功消息
          ElMessage.success('内部生产单创建成功！')
          router.push('/ShowInternalProduction')
        } else {
          console.error('意外的响应格式:', responseData)
          console.error('原始响应:', response)
          ElMessage.error('创建失败，响应格式异常，请查看控制台日志')
        }
      } catch (apiError: any) {
        console.error('API调用错误:', apiError)
        
        // 处理网络错误和服务器错误
        if (apiError.response) {
          // 服务器返回了错误状态码
          const status = apiError.response.status
          const data = apiError.response.data
          
          console.error(`HTTP ${status} 错误详情:`, data)
          
          if (status === 500) {
            const serverError = data?.message || data?.Message || data?.error || '服务器内部错误'
            ElMessage.error(`服务器错误: ${serverError}`)
          } else if (status === 400) {
            const validationError = data?.message || data?.Message || data?.error || '请求参数错误'
            ElMessage.error(`参数错误: ${validationError}`)
          } else if (status === 401) {
            ElMessage.error('请先登录')
          } else if (status === 403) {
            ElMessage.error('权限不足')
          } else if (status === 404) {
            ElMessage.error('API接口不存在')
          } else {
            ElMessage.error(`请求失败 (${status}): ${data?.message || data?.Message || data?.error || '未知错误'}`)
          }
        } else if (apiError.request) {
          // 网络错误（包括超时）
          if (apiError.code === 'ECONNABORTED') {
            ElMessage.error('请求超时，请检查网络连接后重试')
          } else if (apiError.message.includes('timeout')) {
            ElMessage.error('请求超时，请检查网络连接后重试')
          } else {
            ElMessage.error('网络连接失败，请检查网络连接后重试')
          }
          console.error('网络错误:', apiError.request)
        } else {
          // 其他错误
          ElMessage.error(`请求配置错误: ${apiError.message}`)
          console.error('配置错误:', apiError.message)
        }
      } finally {
        submitLoading.value = false
      }
    } else {
      ElMessage.error('请完善必填信息')
    }
  })
}

// 物品选择对话框相关方法
// 加载物品数据
const loadItems = async () => {
  itemLoading.value = true
  try {
    // 构建查询参数
    const params: any = {
      PageIndex: itemPagination.pageIndex,
      PageSize: itemPagination.pageSize,
    }

    // 根据当前物品类型选择不同的API和参数
    if (currentItemType.value === 'product') {
      // 生产物品：使用销售订单物品API
      if (formData.salesOrderNoId && parseInt(formData.salesOrderNoId.toString()) > 0) {
        // 确保传递的是数字类型的ID
        params.SalesOrderId = parseInt(formData.salesOrderNoId.toString())
      }
      
      if (itemSearch.itemCode || itemSearch.itemName) {
        params.SearchKeyword = itemSearch.itemCode || itemSearch.itemName
      }
      
      if (itemSearch.materialType) {
        params.ItemType = itemSearch.materialType
      }
      
      if (itemSearch.category) {
        params.ItemclassificationId = parseInt(itemSearch.category)
      }

      console.log('正在调用销售订单物品API，参数:', params)

      // 使用销售订单物品API
      const response: any = await getSalesOrderItems(params)
      
      console.log('销售订单物品API响应:', response)
      
      if (response) {
        const data = response
        console.log('销售订单物品响应数据:', data)
        
        // 调试：查看实际的字段结构
        if (data.pageData && data.pageData.length > 0) {
          console.log('第一个物品的原始数据结构:', data.pageData[0])
          console.log('字段检查:', {
            '物料类型字段': {
              itemType: data.pageData[0].itemType,
              materialType: data.pageData[0].materialType,
              ItemType: data.pageData[0].ItemType
            },
            '分类字段': {
              itemclassificationId: data.pageData[0].itemclassificationId,
              itemClassificationId: data.pageData[0].itemClassificationId,
              classificationId: data.pageData[0].classificationId
            },
            '库存字段': {
              totalInventory: data.pageData[0].totalInventory,
              totalinventory: data.pageData[0].totalinventory,
              inventory: data.pageData[0].inventory
            }
          })
        }
        
        // 处理返回的数据，映射到前端需要的格式
        itemList.value = data.pageData?.map((item: any) => ({
          // 基础显示字段 - 对应图二显示要求
          itemCode: item.itemCode || '',
          itemName: item.itemName || '',
          specification: item.specification || '',
          unit: item.unit || '',
          materialType: item.itemType || item.materialType || item.ItemType || '',  // 物料类型
          category: getClassificationName(item.itemclassificationId || item.itemClassificationId || item.classificationId) || '', // 物品分类
          inventory: item.totalInventory || item.totalinventory || item.inventory || 0, // 库存
          // 后端需要的核心字段
          id: item.id,
          goodsId: item.id, // 用于后端提交
          // 从API获取的数据
          quantity: item.number || item.quantity || 1, // 从API获取数量
          plannedQuantity: item.planQuantity || item.plannedQuantity || item.number || 1, // 从API获取计划数量
          deliveryDate: item.itemexpiration ? new Date(item.itemexpiration).toISOString().split('T')[0] : (item.deliveryDate || item.expectedDate || ''), // 从API获取交付日期并格式化
          // 保留原始数据以备后用
          rowNumber: item.rowNumber,
          salePrice: item.salePrice,
          brand: item.brand,
          manufacturerModel: item.manufacturerModel,
          upper: item.upper,
          number: item.number,
          itemsImg: item.itemsImg,
          auxiliaryUnits: item.auxiliaryUnits,
          itemsRemark: item.itemsRemark,
          createTime: item.createTime,
          modifyTime: item.modifyTime,
          createName: item.createName,
          modifierName: item.modifierName,
          salesOrderId: item.salesOrderId,
          relationId: item.relationId,
          hasStock: item.hasStock,
          isExpiringSoon: item.isExpiringSoon,
          isExpired: item.isExpired,
          stockStatus: item.stockStatus,
          priceRange: item.priceRange,
          expirationStatus: item.expirationStatus,
          daysToExpiration: item.daysToExpiration
        })) || []
        
        itemTotal.value = data.totalCount || 0
        console.log('处理后的销售订单物品列表:', itemList.value)
        console.log('总数:', itemTotal.value)
      } else {
        console.log('销售订单物品响应数据格式异常:', response)
        ElMessage.error('加载生产物品数据失败：响应数据格式错误')
        itemList.value = []
        itemTotal.value = 0
      }
    } else {
      // 消耗物品：使用物品列表API
      if (itemSearch.itemCode || itemSearch.itemName) {
        params.SearchKeyword = itemSearch.itemCode || itemSearch.itemName
      }
      
      if (itemSearch.materialType) {
        params.ItemType = itemSearch.materialType
      }
      
      if (itemSearch.category) {
        params.ItemclassificationId = parseInt(itemSearch.category)
      }

      console.log('正在调用物品列表API，参数:', params)

      // 使用物品列表API
      const response: any = await getItemss(params)
      
      console.log('物品列表API响应:', response)
      
      if (response) {
        const data = response
        console.log('物品列表响应数据:', data)
        
        // 调试：查看实际的字段结构
        if (data.pageData && data.pageData.length > 0) {
          console.log('第一个物品的原始数据结构:', data.pageData[0])
          console.log('字段检查:', {
            '物料类型字段': {
              itemType: data.pageData[0].itemType,
              materialType: data.pageData[0].materialType,
              ItemType: data.pageData[0].ItemType
            },
            '分类字段': {
              itemclassificationId: data.pageData[0].itemclassificationId,
              itemClassificationId: data.pageData[0].itemClassificationId,
              classificationId: data.pageData[0].classificationId,
              categoryName: data.pageData[0].categoryName
            },
            '库存字段': {
              totalInventory: data.pageData[0].totalInventory,
              totalinventory: data.pageData[0].totalinventory,
              inventory: data.pageData[0].inventory
            }
          })
        }
        
        // 处理返回的数据，映射到前端需要的格式  
        itemList.value = data.pageData?.map((item: any) => ({
          // 基础显示字段 - 对应图二显示要求
          itemCode: item.itemCode || '',
          itemName: item.itemName || '',
          specification: item.specification || '',
          unit: item.unit || '',
          materialType: item.itemType || item.materialType || item.ItemType || '',  // 物料类型
          category: getClassificationName(item.itemclassificationId || item.itemClassificationId || item.classificationId) || item.categoryName || '', // 物品分类
          inventory: item.totalInventory || item.totalinventory || item.inventory || 0, // 库存
          // 后端需要的核心字段
          id: item.id,
          goodsId: item.id, // 用于后端提交
          // 从API获取的数据
          quantity: item.quantity || item.number || 1, // 从API获取数量
          plannedQuantity: item.plannedQuantity || item.planQuantity || 1, // 从API获取计划消耗数量
          warehouseId: item.warehouseId || 0, // 仓库ID
          // 保留原始数据以备后用
          categoryName: item.categoryName,
          state: item.state,
          brand: item.brand,
          salePrice: item.salePrice,
          itemsRemark: item.itemsRemark
        })) || []
        
        itemTotal.value = data.totalCount || 0
        console.log('处理后的物品列表:', itemList.value)
        console.log('总数:', itemTotal.value)
      } else {
        console.log('物品列表响应数据格式异常:', response)
        ElMessage.error('加载消耗物品数据失败：响应数据格式错误')
        itemList.value = []
        itemTotal.value = 0
      }
    }
    
  } catch (apiError: any) {
    console.error('加载物品数据错误:', apiError)
    
    // 处理网络错误和服务器错误
    if (apiError.response) {
      const status = apiError.response.status
      ElMessage.error(`加载物品数据失败 (${status}): ${apiError.response.data?.message || '服务器错误'}`)
    } else if (apiError.request) {
      if (apiError.code === 'ECONNABORTED' || apiError.message.includes('timeout')) {
        ElMessage.error('加载物品数据超时，请检查网络连接后重试')
      } else {
        ElMessage.error('网络连接失败，请检查网络连接后重试')
      }
    } else {
      ElMessage.error(`加载物品数据失败: ${apiError.message}`)
    }
    
    itemList.value = []
    itemTotal.value = 0
  } finally {
    itemLoading.value = false
  }
}

// 搜索物品
const searchItems = () => {
  itemPagination.pageIndex = 1
  loadItems()
}

// 重置物品搜索
const resetItemSearch = () => {
  itemSearch.itemCode = ''
  itemSearch.itemName = ''
  itemSearch.materialType = ''
  itemSearch.category = ''
  itemPagination.pageIndex = 1
  loadItems()
}

// 处理物品选择变化
const handleItemSelectionChange = (selection: any[]) => {
  selectedItems.value = selection
}

// 处理分页大小变化
const handleItemSizeChange = (val: number) => {
  itemPagination.pageSize = val
  itemPagination.pageIndex = 1
  loadItems()
}

// 处理当前页变化
const handleItemCurrentChange = (val: number) => {
  itemPagination.pageIndex = val
  loadItems()
}

// 确认选择物品
const confirmSelectItems = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择至少一个物品')
    return
  }

  selectedItems.value.forEach(item => {
    const newItem = {
      id: item.id, // 保存物品ID，用于提交时使用
      itemCode: item.itemCode,
      itemName: item.itemName,
      specification: item.specification,
      unit: item.unit,
      materialType: item.materialType, // 物料类型
      quantity: item.quantity || 1, // 从API获取的数量
      warehouseId: null, // 仓库ID，默认为空，用户选择
      plannedQuantity: 1, // 计划数量默认为1，用户手动输入
      actualQuantity: 0, // 实际消耗数量，默认为0，用户手动输入
      deliveryDate: item.deliveryDate || '', // 从API获取的交付日期
      remark: '', // 备注默认为空
      inventory: item.inventory, // 库存
      category: item.category // 物品分类
    }

    if (currentItemType.value === 'product') {
      formData.productItems.push(newItem)
    } else {
      formData.consumableItems.push(newItem)
    }
  })

  itemDialogVisible.value = false
  ElMessage.success(`已添加 ${selectedItems.value.length} 个物品`)
}

// 关闭表单
const handleClose = () => {
  router.push('/ShowInternalProduction')
}

// 初始化加载部门列表
getDepartmentList()
</script>

<style scoped>
.add-internal-production-container {
  background: #f5f5f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.form-header {
  background: white;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  padding: 0 20px;
  height: 60px !important;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.form-main {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  overflow-x: hidden;
  max-height: calc(100vh - 120px);
}

.form-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.form-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  padding: 15px 0;
  border-bottom: 2px solid #409eff;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-actions {
  display: flex;
  gap: 10px;
}

.form-content {
  padding: 0 20px;
}

.table-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 15px;
}

/* 专门优化消耗物品表格的滚动显示 */
.table-container :deep(.el-table) {
  max-height: 400px;
  overflow-y: auto;
}

.table-container :deep(.el-table__body-wrapper) {
  max-height: 350px;
  overflow-y: auto;
  overflow-x: auto;
}

/* 为表格添加自定义滚动条样式 */
.table-container :deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.table-container :deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.table-container :deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.table-container :deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.table-summary {
  background: #f5f7fa;
  padding: 10px 20px;
  border-top: 1px solid #dcdfe6;
  text-align: right;
  font-weight: 600;
  color: #303133;
}

.attachment-upload-area {
  width: 100%;
}

.upload-demo {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
  padding: 30px 20px;
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  background: #fafafa;
  transition: all 0.3s ease;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409eff;
  background: #f0f9ff;
}

:deep(.el-upload-dragger.is-dragover) {
  border-color: #409eff;
  background: #e6f7ff;
}

:deep(.el-icon--upload) {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

:deep(.el-upload__text) {
  font-size: 16px;
  color: #606266;
  margin-bottom: 8px;
}

:deep(.el-upload__text em) {
  color: #409eff;
  font-style: normal;
}

:deep(.el-upload__tip) {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.selected-files,
.uploaded-files {
  margin-top: 20px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  background: #fafafa;
}

.files-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #e6e6e6;
  font-weight: 600;
  color: #303133;
}

.files-list {
  max-height: 200px;
  overflow-y: auto;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.file-item:last-child {
  border-bottom: none;
}

.file-item .el-icon {
  font-size: 18px;
  color: #409eff;
}

.file-name {
  flex: 1;
  color: #303133;
  font-weight: 500;
}

.file-size {
  color: #909399;
  font-size: 12px;
}

.upload-time {
  color: #909399;
  font-size: 12px;
  margin-left: 10px;
}

.form-footer {
  background: white;
  border-top: 1px solid #e6e6e6;
  padding: 15px 20px;
  height: 60px !important;
  position: sticky;
  bottom: 0;
  z-index: 100;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

.footer-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__inner) {
  text-align: center;
}

/* 主滚动区域的滚动条样式 */
.form-main::-webkit-scrollbar {
  width: 8px;
}

.form-main::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.form-main::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.form-main::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 确保表单部分有足够的底部间距 */
.form-section:last-child {
  margin-bottom: 50px;
}

/* 销售订单对话框样式 */
.dialog-footer {
  text-align: right;
}

:deep(.el-dialog__body) {
  padding: 10px 20px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #e6e6e6;
  padding: 15px 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #e6e6e6;
  padding: 15px 20px;
}
</style> 